package com.hp.homework;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {
	
	private Socket socket;
	
	private InputStream in;
	
	private PrintStream out;
	
	private final static String ROOT="c:\\test";
	
	public Processor(Socket socket){
		this.socket=socket;
		try {
			in=socket.getInputStream();
			out=new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} 
	
	public void run() {
		String fileName=parse(in);
		sendFile(fileName);
	}
	
	
	public String parse(InputStream in){
		String fileName="";
		BufferedReader br=new BufferedReader(new InputStreamReader(in));
		try {
			String httpMessage=br.readLine();
			//第一部分为id  第二部分为文件名称  第三部分为协议版本号
			String[] content=httpMessage.split(" ");
			if(content.length!=3){
				sendErrorMessage(404, "client error");
			}
			System.out.println(content[0]+"  "+content[1]+"   "+content[2]);
			fileName=content[1];
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return fileName;
	}
	
	public void sendErrorMessage(int ErrorCode,String ErrorContent){
		System.out.println(ErrorContent);
		out.println("HTTP/1.0 "+ErrorCode+" "+ErrorContent);
		out.println("content-type:text/html");
		out.println("<html>");
		out.println("<head>");
		out.println("</head>");
		out.println("<body>");
		out.println("errorCode"+ErrorCode+"errorcontet"+ErrorContent);
		out.println("</body>");
		out.println("</html>");
	}
	
	public void sendFile(String fileName){
		System.out.println(ROOT+fileName);
		File file=new File(ROOT+fileName);
		if(!file.exists()){
			sendErrorMessage(404, "file not fond");
			return ;
		}
		try {
			InputStream is=new FileInputStream(file);
			byte content[]=new  byte[(int)file.length()];
			is.read(content);
			out.println("HTTP/1.0 200 QUERY");
			out.println("content-length"+content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
			is.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
